package com.heima.search.listener;

import com.alibaba.fastjson.JSON;
import com.heima.common.constants.ArticleConstants;
import com.heima.model.search.vo.SearchArticleVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class SyncArticleListener {

    @Autowired
    private RestHighLevelClient restHighLevelClient;// Elasticsearch 客户端实例，用于与 Elasticsearch 交互

    @KafkaListener(topics = ArticleConstants.ARTICLE_ES_SYNC_TOPIC)
    public void onMessage(String message) {
        if(StringUtils.isNotBlank(message)) {
            log.info("SyncArticleListener message:{}",message);

            SearchArticleVo searchArticleVo = JSON.parseObject(message, SearchArticleVo.class);//将 message 解析为 SearchArticleVo 类型的对象，用于后续操作
            // 构建 Elasticsearch 索引请求
            IndexRequest indexRequest = new IndexRequest("app_info_article");//创建 IndexRequest 对象，并设置索引名称为 "app_info_article"
            indexRequest.id(searchArticleVo.getId().toString());//设置文档 ID
            indexRequest.source(message, XContentType.JSON);//设置文档的内容为原始 message，并指定了内容类型为 JSON 格式
            // 同步数据到 Elasticsearch
            try {
                restHighLevelClient.index(indexRequest, RequestOptions.DEFAULT);//将数据写入 Elasticsearch
            } catch (Exception e) {
                e.printStackTrace();
                log.error("同步数据失败！{}",e.getMessage());
            }

        }

    }
}
